package cn.chencq.math;

/**
 * 
 * @ClassName: Sqrt
 * @Description: 求平方根
 * @author: chaoqun.chen
 * @date: 2018年12月12日 下午5:47:13
 */
public class Sqrt {

	public static void main(String[] args) {
		binarySearch(5.00);
		newTonIteration(5.00);
		newTonIteration(0.05);
	}

	/**
	 * 
	 * @Title: binarySearch
	 * @Description: 二分法
	 * @param x
	 * @return double
	 */
	public static double binarySearch(double x) {
		double y = x / 2.00;
		double low = 0.00;
		double up = x;
		int count = 1;
		while (Math.abs(y * y - x) > 1e-8) {
			if (y * y > x) {
				up = y;
				y = low + (y - low) / 2.00;
			} else {
				low = y;
				y = up - (up - y) / 2.00;
			}
			count++;
		}
		System.out.println("查找" + count + "次,结果:" + y);
		return y;
	}

	/**
	 * 
	 * @Title: newTonIteration
	 * @Description: 牛顿迭代法
	 * @param x
	 * @return double
	 */
	public static double newTonIteration(double x) {
		int count = 1;
		double y = x / 2.00;
		while (Math.abs(y * y - x) > 1e-8) {
			y = (y + x / y) / 2.00;
			count++;
		}
		System.out.println("查找" + count + "次,结果:" + y);
		return y;
	}
}
